/*
 * Copyright 2020 lcnap
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package pers.lcnap.simplerpc.rpc.handler;

import com.codahale.metrics.Timer;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import pers.lcnap.RpcRequest;
import pers.lcnap.RpcResponse;
import pers.lcnap.simplerpc.rpc.RpcRuntimeException;
import pers.lcnap.simplerpc.util.BeanContext;
import pers.lcnap.simplerpc.util.MetricUtil;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * 用于 rpc server 端服务调用。
 * 根据{@link RpcRequest},调用相关的实现服务类。目前，只支持引用类型参数。没有对请求检查。
 */
public class ServiceCallChannelHandler extends ChannelInboundHandlerAdapter {

    private final Logger logger = LoggerFactory.getLogger(ServiceCallChannelHandler.class);


    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        final Timer.Context context = MetricUtil.rpcRequestSpendTime.time();

        RpcRequest request = (RpcRequest) msg;

        try {
            Object serviceImpl = BeanContext.getServiceImpl(request.getService());
            if (serviceImpl == null) {
                throw new RpcRuntimeException("No Such Service [" + request.getService() + "#" + request.getMethod() +"]");
            }

            Method method = serviceImpl.getClass()
                    .getDeclaredMethod(request.getMethod(), request.getArgTypes());

            Object result = method.invoke(serviceImpl, request.getArgs());


            RpcResponse response = new RpcResponse(request.getId(), result);

            logger.debug(request.toString());
            logger.debug(response.toString());
            ctx.writeAndFlush(response);

        }
        catch (RpcRuntimeException runtimeException){
            logger.warn(runtimeException.getMessage());
            ctx.writeAndFlush(new RpcResponse(request.getId(), runtimeException));
        } catch (InvocationTargetException invocationTargetException) {
            Throwable targetException = invocationTargetException.getTargetException();
            ctx.writeAndFlush(new RpcResponse(request.getId(), (RpcRuntimeException) targetException));
        } catch (Exception e) {
            logger.warn(e.getMessage());
            ctx.writeAndFlush(new RpcResponse(request.getId(), RpcRuntimeException.cause(e)));
        } finally {
            context.stop();
        }

    }

}
